package com.cslg.ac.demo.service.message;

import java.util.ArrayList;
import java.util.List;

import com.cslg.ac.demo.exception.ParamIllegalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cslg.ac.demo.constant.MessageType;
import com.cslg.ac.demo.dao.jedis.JedisDAO;
import com.cslg.ac.demo.entity.message.Message;
import com.cslg.ac.demo.util.JedisKeyUtil;

@Service
public class MessageService {

	@Autowired
	private JedisDAO jedisDAO;
	
	private static final char MESSAGE_SPLIT = '|';
	private static final char MESSAGE_INNER_SPLIT = '_';
	
	private String getKey(int id, int type)
	{
		String key;
		switch(type)
		{
			case MessageType.SYSTEM_INFORM : key = JedisKeyUtil.UNREAD_SYSTEM_INFORM + id; break ;
			case MessageType.COMMENT : key = JedisKeyUtil.UNREAD_COMMENT + id; break ;
			case MessageType.COMMUNITY_POST : key = JedisKeyUtil.UNREAD_COMMUNITY_POST + id; break;
			case MessageType.PERSONAL_POST : key = JedisKeyUtil.UNREAD_PERSONAL_POST + id; break;
			default : throw new ParamIllegalException("没有符合的类型！");
		}
		return key;
	}
	
	private void appendToEnd(String key, String value, String newItem)
	{
		jedisDAO.set(key, value + (value.equals("") ? "" : MESSAGE_SPLIT) + newItem);
	}
	
	public void addMessage(int userId, int type, long messageId)
	{
		String key = getKey(userId, type);
		String message = jedisDAO.get(key);
		if(message == null)
			message = "";
		///最前面的 "" 不能去掉
		appendToEnd(key, message, "" + messageId + MESSAGE_INNER_SPLIT + type);
	}
	
	public List<Message> getMessage(int id, int type)
	{
		List<Message> messages = new ArrayList<Message>();
		String key = getKey(id, type);
		String value = jedisDAO.get(key);
		if(value != null)
		{
			String[] strs = value.split("\\" + MESSAGE_SPLIT);
			for(String str : strs)
			{
				String[] num = str.split("" + MESSAGE_INNER_SPLIT);
				Message message = new Message();
				message.setId(Integer.valueOf(num[0]));
				message.setType(Integer.valueOf(num[1]));
				messages.add(message);
			}
		}
		jedisDAO.del(key);
		return messages;
	}
	
}
